/*
 * @Author: zzd993
 * @Date: 2023-02-13 16:13:11
 * @LastEditors: zzd993
 * @LastEditTime: 2023-02-13 16:56:36
 * @FilePath: \手写vue2源码\src\globalAPI.js
 * Copyright (c) 2023 by ZZD, All Rights Reserved.
 */
const strats = {};
const LIFECYCLE = ["beforeCreate", "created"];
LIFECYCLE.forEach((hook) => {
  strats[hook] = function (p, c) {
    if (c) {
      if (p) {
        return p.concat(c); 
      } else {
        return [c];   // 儿子有父亲没有，将儿子包装成数组
      }
    } else {
      return p; // 如果儿子没有则用父亲
    }
  };
});
export function initGlobalAPI(Vue) {
  Vue.options = {};
  Vue.mixin = function (mixin) {
    // 我们希望将用户选项和全局的options进行合并
    this.options = mergeOptions(this.options, mixin);
    return this;
  };
}

export function mergeOptions(parent, child) {
  const options = {};
  for (let key in parent) {
    mergeField(key);
  }
  for (let key in child) {
    if (!parent.hasOwnProperty(key)) {
      mergeField(key);
    }
  }
  function mergeField(key) {
    // 用策略模式减少ifelse
    if (strats[key]) {
      options[key] = strats[key](parent[key], child[key]);
    } else {
      // 如果不在策略中则以儿子为主
      options[key] = child[key] || parent[key];
    }
  }
  return options;
}
